<?php



/**
 * Users authenticator.
 */
class Authenticator extends NObject implements IAuthenticator
{
    /** @var NConnection */
    private $database;

    public function __construct(NConnection $database)
    {
        $this->database = $database;
    }

    /**
        * Performs an authentication
        * @param  array
        * @return NIdentity
        * @throws NAuthenticationException
        */
    public function authenticate(array $credentials)
    {
        list($username, $password) = $credentials;
        $row = $this->database->table('agent')->where('email', $username)->where("confirmed", 1)->fetch();

        if (!$row) {
            throw new NAuthenticationException("Uživatel s uživatelským jménem '$username' nebyl nalezen nebo nemá aktivovaný účet.", self::IDENTITY_NOT_FOUND);
        }

        $calcPass = self::calculateHash($password, $row->lastname);
        if ($row->password !== $calcPass) {
            throw new NAuthenticationException("Chybně zadané heslo.", self::INVALID_CREDENTIAL);
        }

        unset($row->password);
        return new NIdentity($row->id, $row->role, $row->toArray());
    }

    /**
     * Vypocet hash kodu hesla
     * @param string $password
     * @param string $salt
     * @return type 
     */
    public static function calculateHash($password, $salt)
    {                
        return sha1($password . str_repeat(substr($salt, -3), 3));
    }

}
